<template>
  <a-modal
    title="操作"
    :width="800"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">

        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="角色名称">
          <a-input placeholder="角色名称"
                   v-decorator="[ 'name', {rules: [{ required: true, message: '请输入。。。' }]}]"
          ></a-input>
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="角色描述">
          <a-input placeholder="角色描述"
                   v-decorator="[ 'description', {rules: [{ required: true, message: '请输入。。。' }]}]"
          ></a-input>
        </a-form-item>

        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="角色类型">
          <a-radio-group v-decorator="[ 'type', {rules: [{ required: true, message: '请选择' }]}]">
            <a-radio :value="1">服务商</a-radio>
            <a-radio :value="2">代理商</a-radio>
            <a-radio :value="3">商户</a-radio>
          </a-radio-group>
        </a-form-item>

        <a-divider/>

        <div v-for="(item, index) in parentMenus" :key="index">
          <a-form-item
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            :label="item.name"
          >
            <a-row :gutter="16" v-for="(permission, index) in item.children" :key="index">
              <a-col :span="4">
                {{ permission.name }}：
              </a-col>
              <a-col :span="20">
                <a-checkbox
                  :indeterminate="permission.indeterminate"
                  :checked="permission.checkedAll"
                  @change="onChangeCheckAll($event, permission)">
                  全选
                </a-checkbox>
                <a-checkbox-group :options="permission.actionsOptions" v-model="permission.actions" @change="onChangeCheck(permission)" />
              </a-col>
            </a-row>
          </a-form-item>
        </div>

      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
  import { selectAll, selectByRoleId } from '@/api/system/menu'
  import { save } from '@/api/system/role'
  import pick from 'lodash.pick'

  export default {
    //--############  data() ###############-->
    data() {
      return {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 }
        },
        visible: false,
        confirmLoading: false,
        mdl: {},
        form: this.$form.createForm(this),

        isDisabled: false,
        parentMenus:[]
      }
    },
    //--############  data() ###############-->

    created() {
      this.loadPermissions()
    },

    //--############  methods() ###############-->
    methods: {
      add() {
        this.isDisabled = false
        this.visible = true
        this.parentMenus.forEach(item => {
          item.children.forEach(permission => {
            permission.actions = []
          })
        })
      },
      edit(record) {
        this.isDisabled = true
        this.mdl = Object.assign({}, record)
        this.visible = true
        //console.log(JSON.stringify(record))
        selectByRoleId(this.mdl.id).then(res =>{
          const result = res.result
          //有权限表，处理勾选
          if (result && this.parentMenus) {
            // 先处理要勾选的权限结构
            const permissionsAction = {}
            result.forEach(permission => {
              permissionsAction[permission.id] = permission.actions
            })
            // 把权限表遍历一遍，设定要勾选的权限 action

            this.parentMenus.forEach(item => {
              item.children.forEach(permission => {
                permission.actions = permissionsAction[permission.id] || []
              })
            })
          }
        })

        this.$nextTick(() => {
          this.form.setFieldsValue(pick(this.mdl, 'name','type', 'description'))
        })
      },
      close() {
        this.$emit('close')
        this.visible = false
        this.form.resetFields()
        this.mdl={}
      },
      handleOk() {
        const _this = this
        // 触发表单验证
        this.form.validateFields((err, values) => {
          // 验证表单没错误
          if (!err) {
            //console.log('form data', JSON.stringify(this.parentMenus))
            values.id = this.mdl.id;
            _this.confirmLoading = true
            // 模拟后端请求 2000 毫秒延迟
            values.menuList = this.parentMenus
            //console.log(JSON.stringify(values))
            save(values).then((res) => {
              if (res.code === 200) {
                _this.$message.success('保存成功')
                _this.$emit('ok')
                _this.close()
              }else {
                this.$notification.error({
                  message: '错误',
                  description: res.message,
                  duration: 4
                })
              }
            }).catch(() => {
              // Do something
            }).finally(() => {
              _this.confirmLoading = false
            })
          }
        })

      },
      handleCancel() {
        this.close()
      },

      onChangeCheck (permission) {
        permission.indeterminate = !!permission.actions.length && (permission.actions.length < permission.actionsOptions.length)
        permission.checkedAll = permission.actions.length === permission.actionsOptions.length
      },
      onChangeCheckAll (e, permission) {
        Object.assign(permission, {
          actions: e.target.checked ? permission.actionsOptions.map(obj => obj.value) : [],
          indeterminate: false,
          checkedAll: e.target.checked
        })
      },
      loadPermissions () {

        const that = this
        selectAll().then(res => {
          const result = res.result
          that.parentMenus = result.map(item => {
            item.children.map(permission => {
              const options = permission.buttonList
              permission.checkedAll = false
              permission.actions = []
              permission.indeterminate = false
              permission.actionsOptions = options.map(option => {
                return {
                  label: option.name,
                  value: option.action
                }
              })
              return permission
            })
            return item
          })
          //console.log("aaa=" + JSON.stringify(that.parentMenus))
        })

      },
    }
    //--############  methods() ###############-->
  }
</script>

<style scoped>

</style>
